// pages/ai_chat/ai_chat_page.dart (*** NEW ***)
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:gpt_markdown/gpt_markdown.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../bloc/ai_chat/ai_chat_bloc.dart';
import '../../bloc/ai_chat/ai_chat_event.dart';
import '../../bloc/ai_chat/ai_chat_state.dart' hide ChatMessage;

import '../../config/app_colors.dart';
import 'chat_message.dart';

class AiPage extends StatefulWidget {
  const AiPage({super.key});

  @override
  State<AiPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<AiPage> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  // Initial chat messages (mimicking the screenshot flow)
  List<Map<String, dynamic>> _messages = [];

  @override
  void initState() {
    super.initState();
    // Simulate initial loading message and then display content
    // Future.delayed(const Duration(seconds: 2), () {
    //   if (mounted) {
    //     setState(() {
    //       _messages.insert(
    //         0,
    //         AiResponseMessage(content: '请稍后，正在分析贵公司企业数据。'),
    //       ); // This is the "loading" message
    //       // In a real scenario, you'd fetch actual data and replace the loading message
    //     });
    //     _scrollToBottom();
    //   }
    // });

    context.read<AiChatBloc>().add(LoadMessage());

    // Automatically scroll to bottom on new messages
    // This is a simplified approach, often you'd listen to _messages.length changes
    // or call _scrollToBottom after adding a message.
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  // --- Helper Functions for UI elements ---


  // 添加这个方法到你的类中
  Widget _buildLoadingMessage(int index) {
    return Align(
      alignment: Alignment.centerLeft,
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
        padding: const EdgeInsets.all(16.0),
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                valueColor: AlwaysStoppedAnimation<Color>(Colors.grey),
              ),
            ),
            const SizedBox(width: 12),
            const Text(
              'AI正在思考中...',
              style: TextStyle(fontSize: 15.0, color: Colors.black87),
            ),
          ],
        ),
      ),
    );
  }


  // Function to build a message bubble based on type
  Widget _buildMessageBubble(Map<String, dynamic> message,int index) {
    switch (message['recordType'] ?? '') {
      case 'user':
        return _buildUserMessage(message,index);
      case 'ai':
        if(message['content'] == null || message['content'] == ''){
          return  _buildLoadingMessage(index);
        }

        return _buildAiMessage(message,index);
      // case 'suggestedQuestions':
      //   return _buildSuggestedQuestions(message);
      // case 'actionButtons':
      //   return _buildActionButtons(message);
      // case 'userMessage':
      //   return _buildUserMessage(
      //     message as UserMessage,
      //   ); // Added for completeness, though not in screenshot
      default:
        return const SizedBox.shrink(); // Fallback
    }
  }

  Widget _buildUserMessage(Map<String, dynamic> message,int index) {
    return Align(
      alignment: Alignment.centerRight,
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Text(
          message['content'] ?? '',
          style: const TextStyle(fontSize: 15.0, color: Colors.black87),
        ),
      ),
    );
  }

  Widget _buildAiMessage(Map<String, dynamic> message,int index) {
    return Align(
      alignment: Alignment.centerLeft,
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
        padding: const EdgeInsets.all(16.0),
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [

            // Markdown(data: message['content'] ?? '',
            //    shrinkWrap: true,
            // ),
            GptMarkdown(
              message['content'] ?? '',
              style: const TextStyle(fontSize: 15.0, color: Colors.black87),
            ),
            const SizedBox(height: 12.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              // Distribute icons evenly  refresh 刷新 volume_up_outlined 语音
              children: [
                _buildActionIcon(Icons.copy, '复制', () => print('复制')),
                _buildActionIcon(
                  Icons.bookmark_border,
                  '收藏',
                  () => print('收藏'),
                ),
                _buildActionIcon(Icons.share, '分享', () => print('分享')),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // Helper for action icons in AI response
  Widget _buildActionIcon(
    IconData icon,
    String tooltip,
    VoidCallback onPressed,
  ) {
    return IconButton(
      icon: Icon(icon, color: Colors.grey[600], size: 20),
      onPressed: onPressed,
      tooltip: tooltip,
      visualDensity: VisualDensity.compact,
      // Make icons a bit denser
      padding: EdgeInsets.zero,
      // Remove extra padding
    );
  }




  // Helper to get specific icons for action buttons (placeholder)
  IconData _getIconForAction(String text) {
    switch (text) {
      case '税款确认':
        return Icons.receipt_long;
      case '工资确认':
        return Icons.attach_money;
      case '进项发票勾选确认':
        return Icons.fact_check_outlined;
      default:
        return Icons.help_outline;
    }
  }

  // --- Input Bar Logic ---
  void _sendMessage(String text) {
    if (text.trim().isEmpty) return;
    var lastmsg = _messages.last;
    if(lastmsg['recordType'] == 'ai' && (lastmsg['content'] == null || lastmsg['content'] == '')){
      EasyLoading.showToast( '请等待回答结束再提问');
      return;
    }
    // setState(() {
    //   _messages.add(UserMessage(content: text));
    // });

    context.read<AiChatBloc>().add(
      SendMessage(HashMap.from({'content': text})),
    );

    setState(() {
      _messages.add(HashMap.from({'recordType': 'user', 'content': text}));
      _messages.add(HashMap.from({'recordType': 'ai', 'content': ''}));
    });
    _messageController.clear();
    _scrollToBottom();
    // Simulate AI response after user message (for demo)
    // _simulateAiResponse(text);
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  RefreshController _refreshController = RefreshController(
    initialRefresh: false,
  );

  _onRefresh() async {
    await Future.delayed(const Duration(seconds: 2));
    _refreshController.refreshCompleted();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true, // 这行是关键
        backgroundColor: AppColors.primaryColor,
        title: const Text(
          '企税AI定制版',
          style: TextStyle(
            color: AppColors.textWhite,
            fontSize: 16.0,
            fontWeight: FontWeight.bold,
          ),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: BlocConsumer<AiChatBloc,AiState>(
              builder: (context, state) {
                if (state is AiChatSuccessState || state is AiChatSuccessRspState) {
                  return ListView.builder(
                    controller: _scrollController,
                    itemCount: _messages.length,
                    padding: const EdgeInsets.symmetric(vertical: 8.0),
                    itemBuilder: (context, index) {
                      return _buildMessageBubble(_messages[index],index);
                    },
                  );
                }
                return SizedBox.shrink();
              },
              listener: (context, state) {
                if (state is AiChatSuccessState || state is AiChatSuccessRspState) {
                  WidgetsBinding.instance.addPostFrameCallback((_) {
                    _scrollToBottom();
                  });
                  // 300ms 后再次滚动
                  Future.delayed(const Duration(milliseconds: 200), () {
                    _scrollToBottom();
                  });
                  // 300ms 后再次滚动
                  Future.delayed(const Duration(milliseconds: 600), () {
                    _scrollToBottom();
                  });

                }
              },
              buildWhen: (previous, current) {
                if (current is AiChatSuccessState) {
                  var list = current.messages['content'];
                  if (list!=null &&  list is List) {
                    // var newList = list as List<Map<String, dynamic>>;
                    var newList = list as List<dynamic>;
                    if(newList.isNotEmpty){
                      _messages = [...newList,..._messages];
                    }
                  }
                }else if(current is AiChatSuccessRspState){
                  var data = current.messages as Map<String,dynamic>;
                  if (data!=null) {
                    // var newList = list as List<Map<String, dynamic>>;
                    var lastmsg = _messages.last;
                    if(lastmsg['recordType'] == 'ai'  && ( lastmsg['content'] == null || lastmsg['content'] == '')){
                      _messages.remove(lastmsg);
                    }
                    _messages.add(data);
                  }
                }
                return current is AiChatSuccessState || current is AiChatSuccessRspState;
              },
            ),
          ),
          // Input area
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 8.0),
            child: Row(
              children: [
                const SizedBox(width: 8),
                Flexible(
                  flex: 1,
                  fit: FlexFit.tight,
                  child: btnChild('工资确认', Icons.receipt_long, () {
                    _sendMessage('工资确认');
                  }),
                ),
                const SizedBox(width: 4),
                Flexible(
                  flex: 1,
                  fit: FlexFit.tight,
                  child: btnChild('纳税确认', Icons.attach_money, () {
                    _sendMessage('纳税确认');
                  }),
                ),
                const SizedBox(width: 2),
                const SizedBox(width: 2),
                Flexible(
                  flex: 1,
                  fit: FlexFit.tight,
                  child: btnChild('收入确认', Icons.fact_check_outlined, () {
                    _sendMessage('收入确认');
                  }),
                ),
                const SizedBox(width: 2),
                Flexible(
                  flex: 1,
                  fit: FlexFit.tight,
                  child: btnChild('成本确认', Icons.help_outline, () {
                    _sendMessage('成本确认');
                  }),
                ),
                const SizedBox(width: 8),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(
              horizontal: 10.0,
              vertical: 8.0,
            ),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                top: BorderSide(color: Colors.grey[200]!, width: 1.0),
              ),
            ),
            child: Row(
              children: [
                IconButton(
                  icon: Icon(
                    Icons.camera_alt_outlined,
                    color: Colors.grey[600],
                  ),
                  onPressed: () => print('Camera clicked'),
                ),
                Expanded(
                  child: TextField(
                    controller: _messageController,
                    decoration: InputDecoration(
                      hintText: '发消息...',
                      hintStyle: TextStyle(color: Colors.grey[400]),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(25.0),
                        borderSide: BorderSide.none,
                        // No border
                      ),
                      filled: true,
                      fillColor: Colors.grey[100],
                      // Light grey background for input
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 16.0,
                        vertical: 10.0,
                      ),
                      isDense: true,
                    ),
                    onSubmitted: (text) => _sendMessage(text),
                    // Send on enter
                    style: const TextStyle(
                      fontSize: 16.0,
                      color: Colors.black87,
                    ),
                  ),
                ),
                IconButton(
                  icon: Icon(
                    Icons.add_circle_outline,
                    color: Theme.of(context).primaryColor,
                  ),
                  // Accent color
                  onPressed: () => print('Plus clicked'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget btnChild(String text, IconData? icon, Function()? onTapClick) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: Colors.grey[300]!, width: 1.0),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 3,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: InkWell(
        onTap: onTapClick,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, size: 16, color: Colors.grey[600]), // Custom icon logic
            const SizedBox(width: 2),
            Text(
              text,
              style: const TextStyle(fontSize: 11.0, color: Colors.black87),
            ),
          ],
        ),
      ),
    );
  }
}
